package com.bsoft.gol.hcb.service.prescriptionCirculation;

import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcb.dao.prescriptionCirculation.*;
import com.bsoft.gol.hcb.service.ClinicGuideService;
import com.bsoft.gol.hcb.utils.CommonUtils;
import com.bsoft.gol.hcb.utils.Constants;
import com.bsoft.gol.hcb.utils.DateUtils;
import com.bsoft.gol.mpi.model.Card;
import com.bsoft.gol.mpi.model.Certificate;
import com.bsoft.gol.mpi.model.Person;
import com.bsoft.gol.mpi.provider.IMPIProvider;
import com.bsoft.gol.mpi.service.MPIException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.security.cipher.sm.SM4Utils;
import ctd.account.UserRoleToken;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.JSONUtils;
import ctd.util.annotation.RpcService;
import hcn.base.BasePropertyConfig;
import hcn.base.BaseTransferPlatform;
import hcn.base.CheckAppointmentRecord;
import hcn.base.Organization;
import hcn.enums.CardTypeEnum;
import hcn.pay.PayType;
import hcn.protocol.base.hisNoticeReq.OffLineSettlementNoticeRequest;
import hcn.protocol.brandnew.dengji.menzhenyuyue.QueryUndeliveredDrugsXmlRequest;
import hcn.protocol.ods.FeeDetailRequestBean;
import hcn.protocol.ods.UnpayedRecordsRequestBean;
import hcn.protocol.ods.newdiagnosis.NewGetFeeDetailResponseBean;
import hcn.protocol.ods.newdiagnosis.NewGetPayedListResponseBean;
import hcn.protocol.ods.newdiagnosis.NewQueryUnPayListResponseBean;
import hcn.response.PrescriptionList;
import hcn.service.ods.vo.NatSubmitRecordVo;
import hcn.util.BaseRespUtil;
import hcn.util.BaseResponse;
import hcn.util.validation.AnnotaionException;
import hcn.util.validation.ValidationUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import pcn.bean.consultation.QueryDrugOrderListQo;
import pcn.bean.consultation.cloudpay.qo.CloudpayQo;
import pcn.bean.consultation.cloudpay.vo.*;
import pcn.bean.express.ExpreeInfoVo;
import pcn.consultation.ConsultAsk;
import pcn.enums.FeeTypeEnum;
import pcn.enums.PrescriptionStateEnum;
import pcn.enums.PrescriptionTypeEnum;
import pcn.prescribe.*;
import pcn.prescriptionCirculation.OdsOrderExpenseDetail;
import pcn.prescriptionCirculation.OdsOrderExpenseRecord;
import pcn.prescriptionCirculation.OdsOrderPrescriptionDrug;
import pcn.prescriptionCirculation.OdsOrderPrescriptionInfo;
import pcn.service.consultation.cloudpay.CloudPayService;
import pcn.vo.consultation.QueryDrugOrderListVo;
import service.rpc.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@SsdevService("cloudPayService")
public class CloudPayServiceImpl implements CloudPayService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CloudPayServiceImpl.class);
    @Autowired
    private PrescriptionInfoIntf prescriptionInfoIntf;
    @Autowired
    private TreatmentApplicationIntf treatmentApplicationIntf;
    @Autowired
    private ConsultAskServiceIntf consultAskServiceIntf;
    @Autowired
    private OdsPrescriptionOrderDAO odsPrescriptionOrderDAO;
    @Autowired
    private OdsOrderToPrescriptionDAO odsOrderToPrescriptionDAO;
    @Autowired
    private DisposalExpenseRecordServiceIntf disposalExpenseRecordServiceIntf;
    @Autowired
    private ServiceOpenIntf serviceOpenService;
    @Autowired
    private DrugOrdersService drugOrderService;
    @Autowired
    private InvoiceIntf invoiceService;
    @Autowired
    private OrganizationInfoIntf organizationInfoService;
    @Autowired
    private DeptInfoServiceIntf deptInfoServiceIntf;
    @Autowired
    private OdsExpressInfoDAO odsExpressInfoDAO;
    @Autowired
    private OdsOrderPrescriptionInfoDAO odsOrderPrescriptionInfoDAO;
    @Autowired
    private OdsOrderPrescriptionDrugDAO odsOrderPrescriptionDrugDAO;
    @Autowired
    private OdsOrderExpenseRecordDAO odsOrderExpenseRecordDAO;
    @Autowired
    private OdsOrderExpenseDetailDAO odsOrderExpenseDetailDAO;
    @Autowired
    private ClinicGuideService clinicGuideService;

    @SsdevReference("gol-mpi.mpiProvider")
    private IMPIProvider mpiProvider;

    public IMPIProvider getMpiProvider() {
        return mpiProvider;
    }

    public void setMpiProvider(IMPIProvider mpiProvider) {
        this.mpiProvider = mpiProvider;
    }

    //待支付列表s
    @Override
    @RpcService
    public List<PrescriptionNotesVo> findCloudPayList(CloudpayQo cloudpayQo) throws ControllerException {
        try {
            List<PrescriptionNotesVo> prescriptionNotesVos = new ArrayList<>();

            if (CommonUtils.isEmpty(cloudpayQo.getOrgId())) {
                throw new ControllerException("机构id不能为空");
            }
            if (CommonUtils.isEmpty(cloudpayQo.getMpiId())) {
                throw new ControllerException("mpiId不能为空");
            }
            List<OdsPrescriptionInfo> odslist = prescriptionInfoIntf.findPrescriptionPayList(cloudpayQo.getOrgId(), cloudpayQo.getMpiId());

            PrescriptionNotesVo prescriptionNotesVo;
            if (CommonUtils.isNotEmpty(odslist)) {
                for (OdsPrescriptionInfo odsPrescriptionInfo : odslist) {
                    Double singlePrice = 0.0;
                    prescriptionNotesVo = new PrescriptionNotesVo();
                    prescriptionNotesVo.setPrescriptionInfoId(odsPrescriptionInfo.getPrescriptionInfoId());
                    prescriptionNotesVo.setConsultType(odsPrescriptionInfo.getConsultType());
                    prescriptionNotesVo.setConsultId(odsPrescriptionInfo.getConsultId());
                    ConsultAsk consultAsk = consultAskServiceIntf.getConsultAsksByConsultId(odsPrescriptionInfo.getConsultId());
                    prescriptionNotesVo.setDeptId(consultAsk.getDeptId());
                    prescriptionNotesVo.setDeptName(consultAsk.getDeptName());
                    prescriptionNotesVo.setExpirationDate(DateUtils.toTimeYY(odsPrescriptionInfo.getExpirationDate()));
                    //prescriptionNotesVo.setPrescriptionStatus(odsPrescriptionInfo.getPrescriptionStatus());
                    if ("1".equals(odsPrescriptionInfo.getPrescriptionType())) {
                        prescriptionNotesVo.setFeeType(FeeTypeEnum.XIYAO.getTitle());
                    } else if ("2".equals(odsPrescriptionInfo.getPrescriptionType())) {
                        prescriptionNotesVo.setFeeType(FeeTypeEnum.CHENGYAO.getTitle());
                    } else if ("3".equals(odsPrescriptionInfo.getPrescriptionType())) {
                        prescriptionNotesVo.setFeeType(FeeTypeEnum.CAOYAO.getTitle());
                    }
                    if ("1".equals(odsPrescriptionInfo.getPayStatus())) {
                        prescriptionNotesVo.setOrderStatus("1");
                    } else if (null != odsPrescriptionInfo.getExpirationDate()) {
                        if (odsPrescriptionInfo.getExpirationDate().getTime() < System.currentTimeMillis()) {
                            prescriptionNotesVo.setOrderStatus("2");
                        } else if ("1".equals(odsPrescriptionInfo.getOrderFlag())) {
                            prescriptionNotesVo.setOrderStatus("1");
                        } else {
                            prescriptionNotesVo.setOrderStatus("0");
                            long time = 0;
                            try {
                                time = DateUtils.getCountTimeMillis(new Date(), odsPrescriptionInfo.getExpirationDate());
                                prescriptionNotesVo.setRemainingSeconds(time);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    List<MedicineListBean> medicineListBeans = new ArrayList<>();
                    List<OdsPrescriptionDrug> odsPrescriptionDrugs = prescriptionInfoIntf.findByPrescriptionInfoId(odsPrescriptionInfo.getPrescriptionInfoId());
                    if (CommonUtils.isEmpty(odsPrescriptionDrugs)) {
                        prescriptionNotesVo.setMedicineList(medicineListBeans);
                    }
                    medicineListBeans = getMedicineListBeanList(odsPrescriptionDrugs);
                    if ("3".equals(odsPrescriptionInfo.getPrescriptionType())) {
                        for (MedicineListBean medicineListBean : medicineListBeans) {
                            Double avPrice = (medicineListBean.getPrice() == null ? 0 : medicineListBean.getPrice()) * (medicineListBean.getQuantity() == null ? 0 : medicineListBean.getQuantity());
                            singlePrice = avPrice + singlePrice;
                        }
                        int number = odsPrescriptionInfo.getNumberOfPackets() == null ? 0 : odsPrescriptionInfo.getNumberOfPackets();
                        prescriptionNotesVo.setTotalPrice(singlePrice * number);
                        prescriptionNotesVo.setTotalQuantity(odsPrescriptionInfo.getNumberOfPackets());
                        prescriptionNotesVo.setMedicinePrice(singlePrice);
                    } else if ("2".equals(odsPrescriptionInfo.getPrescriptionType()) || "1".equals(odsPrescriptionInfo.getPrescriptionType())) {
                        for (MedicineListBean medicineListBean : medicineListBeans) {
                            Double avPrice = (medicineListBean.getPrice() == null ? 0 : medicineListBean.getPrice()) * (medicineListBean.getQuantity() == null ? 0 : medicineListBean.getQuantity());
                            singlePrice = avPrice + singlePrice;
                        }
                        prescriptionNotesVo.setTotalPrice(singlePrice);
                    }
                    prescriptionNotesVo.setMedicineList(medicineListBeans);

                    prescriptionNotesVos.add(prescriptionNotesVo);
                }
            }

            Organization organization = organizationInfoService.getOrgDetailByOrgId(cloudpayQo.getOrgId());
            Person person = mpiProvider.getPerson(cloudpayQo.getMpiId());
            Certificate certificate = person.getCertificate();
            List<DisposalExpenseRecord> disposalExpenseRecords = disposalExpenseRecordServiceIntf.queryByHospitalCode(organization.getLocalOrgId(), certificate.getCertificateNo(), "0");
            if (CommonUtils.isNotEmpty(disposalExpenseRecords)) {
                List<MedicineListBean> medicineListBeans;
                MedicineListBean medicineListBean;
                for (DisposalExpenseRecord disposalExpenseRecord : disposalExpenseRecords) {

                    ConsultAsk consultAsk = consultAskServiceIntf.getConsultAsksByConsultId(disposalExpenseRecord.getConsultId());
                    prescriptionNotesVo = new PrescriptionNotesVo();
                    prescriptionNotesVo.setPrescriptionInfoId(disposalExpenseRecord.getExpenseId());
                    prescriptionNotesVo.setConsultType(consultAsk.getConsultType());
                    prescriptionNotesVo.setConsultId(consultAsk.getConsultId());
                    prescriptionNotesVo.setDeptId(consultAsk.getDeptId());
                    prescriptionNotesVo.setDeptName(consultAsk.getDeptName());
                    if ("1".equals(disposalExpenseRecord.getBillCategoryCode())) {
                        prescriptionNotesVo.setFeeType(FeeTypeEnum.JIANYAN.getTitle());
                    } else if ("2".equals(disposalExpenseRecord.getBillCategoryCode())) {
                        prescriptionNotesVo.setFeeType(FeeTypeEnum.JIANCHA.getTitle());
                    }
                    if ("1".equals(disposalExpenseRecord.getPayStatus())) {
                        prescriptionNotesVo.setOrderStatus("1");
                    }

                    List<DisposalExpenseDetail> disposalExpenseDetails = disposalExpenseRecordServiceIntf.queryDisposalExpenseDetail(disposalExpenseRecord.getExpenseId());
                    if (CommonUtils.isNotEmpty(disposalExpenseDetails)) {
                        medicineListBeans = new ArrayList<>();
                        for (DisposalExpenseDetail disposalExpenseDetail : disposalExpenseDetails) {
                            medicineListBean = new MedicineListBean();
                            medicineListBean.setDrugId(disposalExpenseDetail.getItemId());
                            medicineListBean.setDrugName(disposalExpenseDetail.getItemName());
                            medicineListBean.setQuantity(disposalExpenseDetail.getNumber() == null ? 0 : disposalExpenseDetail.getNumber().doubleValue());
                            medicineListBean.setPrice(disposalExpenseDetail.getPrice() == null ? 0 : disposalExpenseDetail.getPrice().doubleValue());
                            medicineListBean.setPackUnit(disposalExpenseDetail.getUnit());
                            medicineListBeans.add(medicineListBean);
                        }
                        prescriptionNotesVo.setMedicineList(medicineListBeans);
                    }
                    prescriptionNotesVos.add(prescriptionNotesVo);
                }
            }

            return prescriptionNotesVos;
        } catch (ControllerException e) {
            throw new ControllerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("获取待支付列表失败");
        }
    }

    //已支付列表
    @Override
    @RpcService
    public AlreadyPayVo findAlreadyCloudPayList(CloudpayQo cloudpayQo) throws ControllerException {
        AlreadyPayVo alreadyPayVo = new AlreadyPayVo();
        if (CommonUtils.isEmpty(cloudpayQo.getOrgId())) {
            throw new ControllerException("机构id不能为空");
        }
        if (CommonUtils.isEmpty(cloudpayQo.getMpiId())) {
            throw new ControllerException("mpiId不能为空");
        }
        if (0 == cloudpayQo.getStatus()) {
            throw new ControllerException("执行状态不能为空");
        }
        List<OdsPrescriptionOrder> odsPrescriptionOrders = odsPrescriptionOrderDAO.findAlreadyCloudPayList(cloudpayQo.getOrgId(), cloudpayQo.getMpiId());
        if (CommonUtils.isEmpty(odsPrescriptionOrders)) {
            return alreadyPayVo;
        }
        List<PrescriptionOrder> prescriptionOrders = new ArrayList<>();
        for (OdsPrescriptionOrder odsPrescriptionOrder : odsPrescriptionOrders) {
            PrescriptionOrder prescriptionOrder = new PrescriptionOrder();
            prescriptionOrder.setOrderId(odsPrescriptionOrder.getOrderId());
            prescriptionOrder.setFeeDate(DateUtils.toallTime(odsPrescriptionOrder.getPayTime()));
            prescriptionOrder.setInvoiceNumber(odsPrescriptionOrder.getInvoiceNumber());
            prescriptionOrder.setPayStatus(odsPrescriptionOrder.getPayStatus());
            if ("4".equals(odsPrescriptionOrder.getPayStatus())) {
                prescriptionOrder.setInvoiceStatus("0");
            } else {
                prescriptionOrder.setInvoiceStatus("1");
            }

            List<ItemOrder> itemOrders = new ArrayList<>();
            List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderToPrescriptionBy(odsPrescriptionOrder.getOrderId());


            for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
                ItemOrder itemOrder = new ItemOrder();
                itemOrder.setItemName(odsOrderToPrescription.getFeeType());
                itemOrder.setDeptName("执行科室缺字段");
                itemOrder.setDeptAddress("执行科室地址缺字段");
                itemOrder.setStatus(cloudpayQo.getStatus());
                itemOrders.add(itemOrder);
            }
            prescriptionOrder.setItemList(itemOrders);
            prescriptionOrders.add(prescriptionOrder);
        }
        Card card = null;
        Person person = null;
        try {
            card = mpiProvider.getCard(cloudpayQo.getMpiId(), cloudpayQo.getOrgId(), CardTypeEnum.MEDICAL_CARD.getTitle());
        } catch (MPIException e) {
            e.printStackTrace();
        }
        alreadyPayVo.setVisitNumber(card.getCardNo());
        alreadyPayVo.setOrderList(prescriptionOrders);
        return alreadyPayVo;
    }

    //已支付详情
    @Override
    @RpcService
    public OrderNoteDetailVo getAlreadyCloudPayDetail(CloudpayQo cloudpayQo) throws MPIException, ControllerException {
        if (CommonUtils.isEmpty(cloudpayQo.getOrderId())) {
            throw new ControllerException("订单id为空");
        }
        OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(cloudpayQo.getOrderId());
        OrderNoteDetailVo orderNoteDetailVo = new OrderNoteDetailVo();
        orderNoteDetailVo.setOrderId(orderNoteDetailVo.getOrderId());
        Person person = mpiProvider.getPerson(odsPrescriptionOrder.getMpiId());
        orderNoteDetailVo.setAvatar(person.getPhotoFileId());
        orderNoteDetailVo.setName(person.getPersonName());
        orderNoteDetailVo.setBalanceDate(DateUtils.toallTime(odsPrescriptionOrder.getPayTime()));
        orderNoteDetailVo.setBalancePrice(odsPrescriptionOrder.getPayFee());
        orderNoteDetailVo.setTotalPrice(odsPrescriptionOrder.getTotalFee());
        orderNoteDetailVo.setInsuranceType(1);
        orderNoteDetailVo.setPayStatus(odsPrescriptionOrder.getPayStatus());
        orderNoteDetailVo.setPayType(odsPrescriptionOrder.getPayType());
        orderNoteDetailVo.setPayNumber(odsPrescriptionOrder.getAgtOrderNumber());
        orderNoteDetailVo.setRefundDate(null);
        orderNoteDetailVo.setRefundNumber(null);

        List<PrescriptionInfo> prescriptionInfoList = new ArrayList<>();
        List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderToPrescriptionBy(odsPrescriptionOrder.getOrderId());

        for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
            PrescriptionInfo prescriptionInfo = new PrescriptionInfo();
            prescriptionInfo.setPrescriptionInfoId(odsOrderToPrescription.getFeeCode());
            prescriptionInfo.setFeeType(odsOrderToPrescription.getFeeType());
            List<MedicineListBean> medicineListBeans = null;

            if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CAOYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                List<OdsPrescriptionDrug> odsPrescriptionDrugList = prescriptionInfoIntf.findByPrescriptionInfoId(odsOrderToPrescription.getFeeCode());
                medicineListBeans = getMedicineListBeanList(odsPrescriptionDrugList);
            } else if (FeeTypeEnum.JIANYAN.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.JIANCHA.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                medicineListBeans = new ArrayList<>();
                DisposalExpenseRecord disposalExpenseRecord = disposalExpenseRecordServiceIntf.getDisposalExpenseRecordByExpenseId(odsOrderToPrescription.getFeeCode());
                List<DisposalExpenseDetail> disposalExpenseDetails = disposalExpenseRecordServiceIntf.queryDisposalExpenseDetail(disposalExpenseRecord.getExpenseId());
                if (CommonUtils.isNotEmpty(disposalExpenseDetails)) {
                    MedicineListBean detailsBean;
                    for (DisposalExpenseDetail disposalExpenseDetail : disposalExpenseDetails) {
                        detailsBean = new MedicineListBean();
                        detailsBean.setDrugId(disposalExpenseDetail.getItemId());
                        detailsBean.setDrugName(disposalExpenseDetail.getItemName());
                        detailsBean.setQuantity(disposalExpenseDetail.getNumber() == null ? 0 : disposalExpenseDetail.getNumber().doubleValue());
                        detailsBean.setPrice(disposalExpenseDetail.getPrice() == null ? 0 : disposalExpenseDetail.getPrice().doubleValue());
                        medicineListBeans.add(detailsBean);
                    }
                }
            }
            if (CommonUtils.isNotEmpty(medicineListBeans)) {
                prescriptionInfo.setMedicineList(medicineListBeans);
                prescriptionInfoList.add(prescriptionInfo);
            }
        }
        orderNoteDetailVo.setPrescriptionList(prescriptionInfoList);
        return orderNoteDetailVo;
    }

    /**
     * 获取流转平台
     *
     * @param prescriptionInfoIdList
     * @return
     */
    @Override
    @RpcService
    public List<BaseTransferPlatform> findTransformList(List<String> prescriptionInfoIdList) {
        List<BaseTransferPlatform> baseTransferPlatforms = new ArrayList<>();
        return baseTransferPlatforms;
    }


    /**
     * @Author:FangZhiyi
     * @Description 线下支付显示处方或诊间支付支付线上线上处方，更改本地处方表状态
     * @Params [feeRecordList, invoiceCode, orgId]
     * @Return BaseResponse
     * @Data Created in 2020/12/8 16:42
     * @Moddified By:
     */
    @Override
    public BaseResponse offlineCloudPayNotice(List<OffLineSettlementNoticeRequest.FeeRecord> feeRecordList, String invoiceCode, String orgId, String internetOutpatientType) {
        BaseResponse baseResponse = new BaseResponse();
        try {
            for (OffLineSettlementNoticeRequest.FeeRecord feeRecord : feeRecordList) {
                if (feeRecord.getOutpatientType().equals(internetOutpatientType)) {
                    String feeCode = "";
                    String consultId = "";
                    //单据是否为检验检查
                    boolean billIsInspection = false;
                    if (FeeTypeEnum.JIANCHA.getTitle().equals(feeRecord.getFeeTypeCode()) || FeeTypeEnum.JIANYAN.getTitle().equals(feeRecord.getFeeTypeCode())) {
                        billIsInspection = true;
                    }
                    if (billIsInspection) {
                        //单据为检验检查
                        DisposalExpenseRecord disposalExpenseRecord = disposalExpenseRecordServiceIntf.queryRecordByFeeNo(feeRecord.getFeeNo(), orgId);
                        if (null != disposalExpenseRecord) {
                            if (1 == disposalExpenseRecord.getState()) {
                                //已下单的检验检查
                                if ("1".equals(disposalExpenseRecord.getPayStatus())) {
                                    //已支付
                                    return BaseRespUtil.setResultError("订单已支付:" + JSONObject.toJSONString(feeRecord));
                                }
                                feeCode = disposalExpenseRecord.getExpenseId();
                                consultId = disposalExpenseRecord.getConsultId();
                            }
                        }
                    } else {
                        //单据为处方
                        OdsPrescriptionInfo odsPrescriptionInfo = prescriptionInfoIntf.getPrescriptionInfoByOrgId(feeRecord.getFeeNo(), orgId);
                        if (null != odsPrescriptionInfo) {
                            if ("1".equals(odsPrescriptionInfo.getOrderFlag())) {
                                //已下单的处方
                                if ("1".equals(odsPrescriptionInfo.getPayStatus())) {
                                    //已支付
                                    return BaseRespUtil.setResultError("订单已支付:" + JSONObject.toJSONString(feeRecord));
                                }
                                feeCode = odsPrescriptionInfo.getPrescriptionInfoId();
                                consultId = odsPrescriptionInfo.getConsultId();
                            }
                        }
                    }
                    //未支付，取消订单
                    List<String> orderIdList = odsOrderToPrescriptionDAO.findOrderIdByFeeCode(feeCode, consultId);
                    if (!CollectionUtils.isEmpty(orderIdList)) {
                        //云支付有下过订单
                        for (String orderId : orderIdList) {
                            OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(orderId);
                            if (null != odsPrescriptionOrder && "0".equals(odsPrescriptionOrder.getPayStatus())) {
                                //未支付,取消订单
                                drugOrderService.cancelOrder(orderId);
                            }
                        }
                    }

                    if (billIsInspection) {
                        //检验检查改为改为已支付
                        disposalExpenseRecordServiceIntf.updateDisposalExpenseFeeNo(invoiceCode, feeRecord.getFeeNo());
                    } else {
                        //处方单据改为已支付
                        prescriptionInfoIntf.updatePrescriptionByFeeNo(invoiceCode, feeRecord.getFeeNo());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse.setMessage("更新处方：" + JSONObject.toJSONString(feeRecordList) + "出错:" + e.getMessage());
            baseResponse.setCode(-100);
        }
        return baseResponse;
    }


    private List<MedicineListBean> getMedicineListBeanList(List<OdsPrescriptionDrug> odsPrescriptionDrugList) {
        List<MedicineListBean> medicineListBeans = new ArrayList<>();
        for (OdsPrescriptionDrug odsPrescriptionDrug : odsPrescriptionDrugList) {
            MedicineListBean medicineListBean = new MedicineListBean();
            medicineListBean.setDrugId(odsPrescriptionDrug.getDrugId().toString());
            medicineListBean.setDrugName(odsPrescriptionDrug.getDrugName());
            medicineListBean.setDose(odsPrescriptionDrug.getDose() == null ? 0 : odsPrescriptionDrug.getDose().doubleValue());
            medicineListBean.setDoseUnit(odsPrescriptionDrug.getDoseUnit());
            medicineListBean.setFrequencyCode(odsPrescriptionDrug.getFrequencyCode());
            medicineListBean.setTakeDays(odsPrescriptionDrug.getTakeDays() == null ? 0 : odsPrescriptionDrug.getTakeDays());
            medicineListBean.setSpecification(odsPrescriptionDrug.getSpecification());
            medicineListBean.setUsageName(odsPrescriptionDrug.getUsageName());
            medicineListBean.setQuantity(odsPrescriptionDrug.getQuantity() == null ? 0 : odsPrescriptionDrug.getQuantity().doubleValue());
            medicineListBean.setDecoctionCode(odsPrescriptionDrug.getDecoctionCode());
            medicineListBean.setDecoctionName(odsPrescriptionDrug.getDecoctionName());
            medicineListBean.setPackUnit(odsPrescriptionDrug.getPackUnit());
            medicineListBean.setPrice(odsPrescriptionDrug.getPrice() == null ? 0 : odsPrescriptionDrug.getPrice().doubleValue());
            medicineListBeans.add(medicineListBean);
        }

        return medicineListBeans;
    }

    /**
     * @description: 转化处方药品为诊间支付回参
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/6/18 18:26
     * @param: odsPrescriptionInfo
     * @param: odsPrescriptionDrugList
     * @return: java.util.List<hcn.protocol.ods.newdiagnosis.NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean>
     */
    private List<NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean> getDetailsItemsBeanList(OdsPrescriptionInfo odsPrescriptionInfo, List<OdsPrescriptionDrug> odsPrescriptionDrugList, NewQueryUnPayListResponseBean.MergingItemsBean mergingItemsBean) {

        List<NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean> medicineListBeans = new ArrayList<>();
        NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean medicineListBean;

        //西药、中成药单个药品总金额，单价×数量
        BigDecimal totalFee;
        //药方的总金额
        BigDecimal medicineTotalFee = new BigDecimal(0);
        //中草药的一帖的价格
        BigDecimal chineseMedicinePrice = new BigDecimal(0);
        //草药方的药品名称拼接
        StringBuffer chineseMedicineName = new StringBuffer();
        //遍历处方药品
        for (OdsPrescriptionDrug odsPrescriptionDrug : odsPrescriptionDrugList) {
            medicineListBean = new NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean();
            totalFee = new BigDecimal(0);
            //药品单价
            BigDecimal price = odsPrescriptionDrug.getPrice() == null ? new BigDecimal(0) : new BigDecimal(odsPrescriptionDrug.getPrice().doubleValue());
            //药品数量、重量
            Double quantity = odsPrescriptionDrug.getQuantity() == null ? 0 : odsPrescriptionDrug.getQuantity().doubleValue();
            //单个药品总金额
            totalFee = totalFee.add(price.multiply(new BigDecimal(quantity.doubleValue()))).setScale(2, BigDecimal.ROUND_HALF_UP);

            //若是西药房和中成药方，就组装单个药品
            if (PrescriptionTypeEnum.WESRERN_MEDICINE.getTitle().equals(odsPrescriptionInfo.getPrescriptionType()) || PrescriptionTypeEnum.CHINESE_PATENT_MEDICINE.getTitle().equals(odsPrescriptionInfo.getPrescriptionType())) {
                medicineListBean.setItemName(odsPrescriptionDrug.getDrugName());
                medicineListBean.setSpecifications(odsPrescriptionDrug.getSpecification());
                medicineListBean.setPrice(odsPrescriptionDrug.getPrice().doubleValue());
                medicineListBean.setItemNumber(quantity.toString());
                medicineListBean.setUnit(odsPrescriptionDrug.getPackUnit());
                medicineListBean.setAmount(totalFee.doubleValue());
                //西药和中成药每个都添加到明细里
                medicineListBeans.add(medicineListBean);
                medicineTotalFee = medicineTotalFee.add(totalFee);

            } else if (PrescriptionTypeEnum.CHINESE_MEDICINE.getTitle().equals(odsPrescriptionInfo.getPrescriptionType())) {
                //中草药方的费用名称为该处方的所有药品与数量单位的拼接，把数量和单位放在英文括号中，各药品之间用四个空格分隔。
                // 比如一个中草药处方有8味药，itemName字段的值示例如下:人参(4g) 卜芥(4g) 丁香(4g) 刀豆(4g) 干姜(4g) 广白(4g) 大蓟(4g) 山丹(4g)
                chineseMedicineName.append(odsPrescriptionDrug.getDrugName()).append("(").append(odsPrescriptionDrug.getQuantity()).append(odsPrescriptionDrug.getPackUnit()).append(")").append(" ");
                //处方贴数
                Integer numberOfPackets = odsPrescriptionInfo.getNumberOfPackets() == null ? 0 : odsPrescriptionInfo.getNumberOfPackets();
                //一帖处方价格
                chineseMedicinePrice = chineseMedicinePrice.add(totalFee);
                //草药方的所有贴数
                medicineTotalFee = medicineTotalFee.add(totalFee.multiply(new BigDecimal(numberOfPackets))).setScale(2, BigDecimal.ROUND_HALF_UP);
            }

        }

        //中药处方，就返回合并后的处方结果
        if (PrescriptionTypeEnum.CHINESE_MEDICINE.getTitle().equals(odsPrescriptionInfo.getPrescriptionType())) {
            medicineListBean = new NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean();
            medicineListBean.setItemName(chineseMedicineName.toString());
            //中草药方的数量为该药方的帖数,如：五帖，该字段值传：共五帖
            medicineListBean.setItemNumber(String.valueOf(odsPrescriptionInfo.getNumberOfPackets()));
            medicineListBean.setPrice(chineseMedicinePrice.doubleValue());
            //中草药方的金额为该处方的金额
            medicineListBean.setAmount(medicineTotalFee.doubleValue());
            //草药方只返回一个
            medicineListBeans.add(medicineListBean);
            mergingItemsBean.setMergingName("草药处方");
            mergingItemsBean.setMergingSubtotal(medicineTotalFee.doubleValue());
        } else if (PrescriptionTypeEnum.WESRERN_MEDICINE.getTitle().equals(odsPrescriptionInfo.getPrescriptionType())) {
            mergingItemsBean.setMergingName("西药处方");
            mergingItemsBean.setMergingSubtotal(medicineTotalFee.doubleValue());
        } else if (PrescriptionTypeEnum.CHINESE_PATENT_MEDICINE.getTitle().equals(odsPrescriptionInfo.getPrescriptionType())) {
            mergingItemsBean.setMergingName("中成药处方");
            mergingItemsBean.setMergingSubtotal(medicineTotalFee.doubleValue());
        }
        return medicineListBeans;
    }


    /**
     * @description: 云支付的已支付列表，数据返回和诊间支付的数据返回一致，在hcn-web通过Client.rpcInvoke调用
     * @author: chenJij@bsoft.com.cn
     */
    @RpcService
    public List<NewGetPayedListResponseBean> queryLocalPayedRecords(UnpayedRecordsRequestBean request) throws ControllerException {
        List<NewGetPayedListResponseBean> list = new ArrayList<>();
        NewGetPayedListResponseBean payedListResponseBean = new NewGetPayedListResponseBean();

        //2022年10月26日15:33:26  没有今日支付了，就显示全部的支付记录
        //1 今日支付    2 全部记录    3 未执行
        Integer executionType = request.getExecutionType();
        List<OdsPrescriptionOrder> odsPrescriptionOrders = null;
        //查询今日支付记录
        if (1 == executionType.intValue()) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            Date beginTime = calendar.getTime();
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            Date endTime = calendar.getTime();
            odsPrescriptionOrders = odsPrescriptionOrderDAO.findAlreadyCloudPayListByPayTime(request.getOrgId(), request.getMpiId(), beginTime, endTime);
        } else {
            odsPrescriptionOrders = odsPrescriptionOrderDAO.findAlreadyCloudPayList(request.getOrgId(), request.getMpiId());
        }

        if (CommonUtils.isEmpty(odsPrescriptionOrders)) {
            return list;
        }
        List<NewGetPayedListResponseBean.InvoiceListBean> prescriptionOrders = new ArrayList<>();

        Card card = null;
        Certificate certificate;
        List<QueryUndeliveredDrugsXmlRequest.PatientIdentityCardList> patientIdentityCardList = null;
        try {
            card = mpiProvider.getCard(request.getMpiId(), CardTypeEnum.MEDICAL_CARD.getTitle(), request.getOrgId());
            certificate = mpiProvider.getCertificate(request.getMpiId());
            if(null != certificate){
                patientIdentityCardList = new ArrayList<>();
                QueryUndeliveredDrugsXmlRequest.PatientIdentityCardList identityCardList = new QueryUndeliveredDrugsXmlRequest.PatientIdentityCardList();
                identityCardList.setCardNumber(SM4Utils.decryptData_ECB(certificate.getCertificateNo()));
                identityCardList.setCardType(certificate.getCertificateType());
                patientIdentityCardList.add(identityCardList);

            }
        } catch (MPIException e) {
            e.printStackTrace();
        }

        Organization organization = organizationInfoService.getOrgDetailByOrgId(request.getOrgId());

        //查询这段时间之后的取药列表
        List<String> collect = null;
        QueryUndeliveredDrugsXmlRequest xmlRequest = new QueryUndeliveredDrugsXmlRequest();
        xmlRequest.setOrganizationId(organization.getLocalOrgId());
        xmlRequest.setPrescriptionState(PrescriptionStateEnum.MEDICATION_TAKEN.getState());
        xmlRequest.setDispensingDateTimeStart(DateUtils.toStringForYYYYMMddHHmmss(odsPrescriptionOrders.get(0).getCreateTime()));
        xmlRequest.setDispensingDateTimeEnd(DateUtils.toStringForYYYYMMddHHmmss(new Date()));
        xmlRequest.setPatientIdLists(null);
        xmlRequest.setQueryType(2);
        xmlRequest.setPatientMedicalCardList(null);
        xmlRequest.setPatientIdentityCardList(patientIdentityCardList);
        xmlRequest.setPageNo(1);
        xmlRequest.setPageSize(1000);

        List<PrescriptionList> prescriptionLists =  clinicGuideService.queryDrugTakingList(xmlRequest);
        if(CommonUtils.isNotEmpty(prescriptionLists)){
            collect = prescriptionLists.stream().map(PrescriptionList::getPrescriptionRecordId).collect(Collectors.toList());
        }

        if(CommonUtils.isNotEmpty(collect)){
            List<String> prescriptionInfoIdList = prescriptionInfoIntf.queryPrescriptionInfoIdList(request.getOrgId(), collect);
            if(CommonUtils.isNotEmpty(prescriptionInfoIdList)){
                collect.addAll(prescriptionInfoIdList);
            }
        }

        for (OdsPrescriptionOrder odsPrescriptionOrder : odsPrescriptionOrders) {
            NewGetPayedListResponseBean.InvoiceListBean invoiceListBean = new NewGetPayedListResponseBean.InvoiceListBean();

            if (null != card) {
                invoiceListBean.setPatientId(card.getCardNo());
            } else {
                //TODO 就诊卡目前没值,临时赋值
                invoiceListBean.setPatientId(String.valueOf(System.currentTimeMillis()));
            }

            invoiceListBean.setOrderId(odsPrescriptionOrder.getOrderId());
            BigDecimal totalFee = odsPrescriptionOrder.getTotalFee() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(odsPrescriptionOrder.getTotalFee()));

            invoiceListBean.setCostDate(DateUtils.toallTime(odsPrescriptionOrder.getPayTime()));
            invoiceListBean.setFeeDate(DateUtils.toallTime(odsPrescriptionOrder.getPayTime()));

            invoiceListBean.setInvoiceNumber(odsPrescriptionOrder.getInvoiceNumber());
            invoiceListBean.setPaymentNumber(odsPrescriptionOrder.getPaymentNumber());
            //invoiceListBean支付状态 0 已支付  1以退款  2未知
            //odsPrescriptionOrder支付状态 0：待支付·    1：已支付    2：支付超时   3 已取消   4 已退费
            if ("1".equals(odsPrescriptionOrder.getPayStatus())) {
                invoiceListBean.setPayStatus("1");
            } else if ("4".equals(odsPrescriptionOrder.getPayStatus())) {
                invoiceListBean.setPayStatus("3");
            } else {
                invoiceListBean.setPayStatus("2");
            }
            invoiceListBean.setInvoiceStatus("0");
//            if ("4".equals(odsPrescriptionOrder.getPayStatus())) {
//                invoiceListBean.setInvoiceStatus("1");
//            } else {
//                invoiceListBean.setInvoiceStatus("0");
//            }

            List<NewGetPayedListResponseBean.InvoiceListBean.CostListBean> costListBeans = new ArrayList<>();
            List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderToPrescriptionBy(odsPrescriptionOrder.getOrderId());

            for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
                NewGetPayedListResponseBean.InvoiceListBean.CostListBean costListBean = new NewGetPayedListResponseBean.InvoiceListBean.CostListBean();
                FeeTypeEnum feeTypeEnum = FeeTypeEnum.getDescription(odsOrderToPrescription.getFeeType());
                if (null != feeTypeEnum) {
                    costListBean.setItemName(feeTypeEnum.getContext());
                }

                //executionStatus : 执行判别（0、已付款/未执行/待执行，1、表示已取药2、表示已执行3、标志已退费
                costListBean.setExecutionStatus("0");

                String execute = odsPrescriptionOrder.getOperatePlatformStoreName();
                String remark = odsPrescriptionOrder.getOperatePlatformStoreName();
                if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CAOYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                    OdsExpressInfo odsExpressInfo = odsExpressInfoDAO.getOdsExpressInfo(odsOrderToPrescription.getOrderId());
                    if (Constants.ONE.toString().equals(odsExpressInfo.getTakeWay())) {
                        execute = "物流配送";
                        remark = "待发货";
                    }
                    List<ExpreeInfoVo> expreeInfoVoList = drugOrderService.queryExpressInfo(odsOrderToPrescription.getOrderId());
                    if (CommonUtils.isNotEmpty(expreeInfoVoList)) {
                        for (ExpreeInfoVo expreeInfoVo : expreeInfoVoList) {
                            execute = execute + " " + expreeInfoVo.getExpreeCompanyName();
                            if (Constants.ZERO.toString().equals(expreeInfoVo.getDeliverFlag()) || CommonUtils.isNull(expreeInfoVo.getExpreeNumber())) {
                                remark = "待发货";
                            } else {
                                remark = "查看物流";

                                if (Constants.ONE.toString().equals(expreeInfoVo.getDeliverFlag())) {
                                    costListBean.setConfirmReceiptFlag("1");
                                }
                            }
                        }
                    }

                    if(null != collect){
                        if(collect.contains(odsOrderToPrescription.getFeeCode())){
                            costListBean.setExecutionStatus("1");
                        }
                    }

                } else if (FeeTypeEnum.KDF.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                    //应产品的要求，支付总金额减去快递费
                    totalFee = totalFee.subtract(new BigDecimal(String.valueOf(odsOrderToPrescription.getTotalFee())));
                }
                if (FeeTypeEnum.JIANYAN.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.JIANCHA.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                    OdsOrderExpenseRecord expense = odsOrderExpenseRecordDAO.getOdsOrderExpenseRecordByOrderIdAndExpenseId(odsPrescriptionOrder.getOrderId(), odsOrderToPrescription.getFeeCode());
                    execute = expense.getExecutiveDepartmentName();
                    remark = expense.getExecutiveDepartmentName();
                    costListBean.setItemName(expense.getItemName());
                    costListBean.setExpenseType(odsOrderToPrescription.getFeeType());
                }
                costListBean.setExecute(execute);
                costListBean.setRemark(remark);

                //应产品的要求，不返回快递费明细
                if (!FeeTypeEnum.KDF.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                    //executionType 2待执行   3已完成
                    if (3 == request.getExecutionType() && "1".equals(costListBean.getExecutionStatus())) {
                        costListBeans.add(costListBean);
                    } else if (2 == request.getExecutionType() && "0".equals(costListBean.getExecutionStatus())) {
                        costListBeans.add(costListBean);
                    }
                }
            }

            invoiceListBean.setTotalFee(totalFee.doubleValue());
            invoiceListBean.setAmount(totalFee.toString());

            invoiceListBean.setCostList(costListBeans);
            if(CommonUtils.isNotEmpty(costListBeans)){
                prescriptionOrders.add(invoiceListBean);
            }
        }

        Person person = null;

        if (card != null) {
            payedListResponseBean.setPatientMedicalCardNumber(card.getPatientCode());
            payedListResponseBean.setPatientCode(card.getPatientCode());
        }

        if (null != person) {
            if (null != person.getDob()) {
                payedListResponseBean.setPatientAge(String.valueOf(DateUtils.getAgeByBirth(person.getDob())));
            }
            payedListResponseBean.setPatientName(person.getPersonName());
            payedListResponseBean.setPatientSex(person.getSex());
        }

        // 进行降序排列
        Collections.sort(prescriptionOrders, new Comparator<NewGetPayedListResponseBean.InvoiceListBean>() {
            public int compare(NewGetPayedListResponseBean.InvoiceListBean o1, NewGetPayedListResponseBean.InvoiceListBean o2) {
                Long o1Times = CommonUtils.isEmpty(o1.getFeeDate()) ? 0L : DateUtils.toDate(o1.getCostDate(), "yyyy-MM-dd HH:mm:ss").getTime();
                Long o2Times = CommonUtils.isEmpty(o2.getFeeDate()) ? 0L : DateUtils.toDate(o2.getCostDate(), "yyyy-MM-dd HH:mm:ss").getTime();
                return o2Times.compareTo(o1Times);
            }
        });

        payedListResponseBean.setInvoiceList(prescriptionOrders);
        list.add(payedListResponseBean);
        return list;
    }


    /**
     * @description: 云支付的已支付详情，数据返回和诊间支付的数据返回一致，在hcn-web通过Client.rpcInvoke调用
     * @author: chenJij@bsoft.com.cn
     */
    @RpcService
    public NewGetFeeDetailResponseBean queryLocalPayedRecordDetail(FeeDetailRequestBean request) throws MPIException, ControllerException {
        Organization organization = new Organization();
        if (CommonUtils.isEmpty(request.getOrderId())) {
            throw new ControllerException("订单id为空");
        }
        NewGetFeeDetailResponseBean feeDetailResponseBean = new NewGetFeeDetailResponseBean();
        OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(request.getOrderId());
        if (CommonUtils.isNotEmpty(odsPrescriptionOrder)){
            organization = organizationInfoService.getOrgDetailByOrgId(odsPrescriptionOrder.getOrgId());
        }
        if (CommonUtils.isNotEmpty(organization)) {
            feeDetailResponseBean.setHospitalCode(organization.getLocalOrgId());
            feeDetailResponseBean.setOrganizationId(organization.getLocalOrgId());
        }
        Person person = mpiProvider.getPerson(odsPrescriptionOrder.getMpiId());
        if (CommonUtils.isNotEmpty(person)) {
            feeDetailResponseBean.setAvatar(person.getPhotoFileId());
            feeDetailResponseBean.setUserName(person.getPersonName());
        }
        if (CommonUtils.isNotEmpty(odsPrescriptionOrder))
            feeDetailResponseBean.setRefundTime(odsPrescriptionOrder.getPayTime() + "");

        BigDecimal payFee = new BigDecimal(String.valueOf(odsPrescriptionOrder.getPayFee()));
        BigDecimal totalFee = new BigDecimal(String.valueOf(odsPrescriptionOrder.getTotalFee()));

        feeDetailResponseBean.setInsuranceType("自费");
        feeDetailResponseBean.setPayType(PayType.getDisplay(odsPrescriptionOrder.getPayType()));
        feeDetailResponseBean.setInvoiceNumber(odsPrescriptionOrder.getInvoiceNumber());
        feeDetailResponseBean.setAgtOrderNumber(odsPrescriptionOrder.getAgtOrderNumber());
        feeDetailResponseBean.setPaymentNumber(odsPrescriptionOrder.getPaymentNumber());

        //查询发票信息
        try {
            Map<String, Object> requestMap = Maps.newHashMap();
            requestMap.put("organizationId", organization.getLocalOrgId());
            requestMap.put("queryType", Constants.FOUR);
            requestMap.put("invoiceCode", odsPrescriptionOrder.getInvoiceNumber());
            requestMap.put("paymentNumber", odsPrescriptionOrder.getPaymentNumber());
            List<Map<String, Object>> patientIdentityCardList = Lists.newArrayList();
            Map<String, Object> cardMap = Maps.newHashMap();
            cardMap.put("cardNumber", person.getCertificate().getCertificateNo());
            cardMap.put("cardType", person.getCertificate().getCertificateType());
            requestMap.put("patientIdentityCardList", patientIdentityCardList);
            Map<String, Object> invoiceMap = invoiceService.queryInvoiceInfo(requestMap);
            if (CommonUtils.isNotEmpty(invoiceMap)) {
                if (CommonUtils.isNotEmpty(invoiceMap.get("billBatchCode"))) {
                    feeDetailResponseBean.setBillBatchCode(invoiceMap.get("billBatchCode").toString());
                }
                if (CommonUtils.isNotEmpty(invoiceMap.get("billNo"))) {
                    feeDetailResponseBean.setBillNo(invoiceMap.get("billNo").toString());
                }
                if (CommonUtils.isNotEmpty(invoiceMap.get("random"))) {
                    feeDetailResponseBean.setRandom(invoiceMap.get("random").toString());
                }
            }
        } catch (Throwable throwable) {
            LOGGER.info("获取电子票据失败", throwable.getMessage());
        }

        List<NewGetFeeDetailResponseBean.DetailsBeanX> prescriptionInfoList = new ArrayList<>();
        //查询订单明细
        List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderToPrescriptionBy(odsPrescriptionOrder.getOrderId());

        for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
            NewGetFeeDetailResponseBean.DetailsBeanX detailsBeanX = new NewGetFeeDetailResponseBean.DetailsBeanX();
            detailsBeanX.setConsultId(odsOrderToPrescription.getConsultId());
            detailsBeanX.setFeeTypeCode(odsOrderToPrescription.getFeeType());
            detailsBeanX.setFeeTypeName(FeeTypeEnum.getDescription(odsOrderToPrescription.getFeeType()).getContext());
            detailsBeanX.setFeeNo(odsOrderToPrescription.getFeeCode());
            List<NewGetFeeDetailResponseBean.DetailsBeanX.DetailsBean> medicineListBeans = null;
            //返回处方明细
            if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CAOYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                //从订单处方记录表查询数据
                OdsOrderPrescriptionInfo odsOrderPrescriptionInfo = odsOrderPrescriptionInfoDAO.getByOrderIdAndPrescriptionInfoId(odsOrderToPrescription.getOrderId(), odsOrderToPrescription.getFeeCode());
                detailsBeanX.setFeeNo(odsOrderPrescriptionInfo.getPrescriptionId());
                List<OdsOrderPrescriptionDrug> odsOrderPrescriptionDrugList = odsOrderPrescriptionDrugDAO.findByOrderPrescriptionInfoId(odsOrderPrescriptionInfo.getOrderPrescriptionInfoId());
                medicineListBeans = getFeeListBeanList(odsOrderToPrescription.getFeeType(), odsOrderPrescriptionInfo, odsOrderPrescriptionDrugList);
                //返回检验、检查明细
            } else if (FeeTypeEnum.JIANYAN.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.JIANCHA.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                medicineListBeans = new ArrayList<>();
                //从订单医技记录表查询数据
                OdsOrderExpenseRecord odsOrderExpenseRecord = odsOrderExpenseRecordDAO.getOdsOrderExpenseRecordByOrderIdAndExpenseId(odsOrderToPrescription.getOrderId(),odsOrderToPrescription.getFeeCode());
                if (CommonUtils.isNotEmpty(odsOrderExpenseRecord)) {
                    if (FeeTypeEnum.JIANYAN.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                        detailsBeanX.setExamineRequisitionRecordId(prescriptionInfoIntf.getExamineIdByApplicationNo(odsOrderExpenseRecord.getApplicationNo(), organization.getLocalOrgId()));
                    }
                    if (FeeTypeEnum.JIANCHA.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                        detailsBeanX.setCheckRequisitionRecordId(prescriptionInfoIntf.getCheckIdByApplicationNo(odsOrderExpenseRecord.getApplicationNo(), organization.getLocalOrgId()));
                    }
                    List<OdsOrderExpenseDetail> odsOrderExpenseDetails = odsOrderExpenseDetailDAO.findByOrderExpenseId(odsOrderExpenseRecord.getOrderExpenseId());
                    if (CommonUtils.isNotEmpty(odsOrderExpenseDetails)) {
                        NewGetFeeDetailResponseBean.DetailsBeanX.DetailsBean detailsBean;
                        for (OdsOrderExpenseDetail odsOrderExpenseDetail : odsOrderExpenseDetails) {
                            detailsBean = new NewGetFeeDetailResponseBean.DetailsBeanX.DetailsBean();
                            detailsBean.setItemCode(odsOrderExpenseDetail.getItemId());
                            detailsBean.setItemName(odsOrderExpenseDetail.getItemName());
                            detailsBean.setDosageUnit(odsOrderExpenseDetail.getUnit());
                            detailsBean.setQuantity(odsOrderExpenseDetail.getNumber() == null ? "0" : odsOrderExpenseDetail.getNumber().toString());
                            //检验检查复制quantity
                            detailsBean.setDosage(detailsBean.getQuantity());
                            detailsBean.setPrice(odsOrderExpenseDetail.getPrice() == null ? "0" : odsOrderExpenseDetail.getPrice().toString());
                            detailsBean.setTotalFee(odsOrderExpenseDetail.getAmount() == null ? "0" : odsOrderExpenseDetail.getAmount().toString());
                            medicineListBeans.add(detailsBean);
                        }
                    }
                    detailsBeanX.setApplicationNo(odsOrderExpenseRecord.getApplicationNo());
                }
            } else if (FeeTypeEnum.KDF.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                //应产品的要求，支付总金额减去快递费
                payFee = payFee.subtract(new BigDecimal(String.valueOf(odsOrderToPrescription.getTotalFee())));
                totalFee = totalFee.subtract(new BigDecimal(String.valueOf(odsOrderToPrescription.getTotalFee())));
            }

            detailsBeanX.setDetails(medicineListBeans);
            detailsBeanX.setTotalFee(odsOrderToPrescription.getTotalFee() + "");
            detailsBeanX.setPayStatus(odsPrescriptionOrder.getPayStatus());
            detailsBeanX.setPatientName(person.getPersonName());
            detailsBeanX.setFeeDate(DateUtils.toStringForYYYYMMddHHmmss(odsPrescriptionOrder.getPayTime()));
            //应产品的要求，不返回快递费明细
            if (!FeeTypeEnum.KDF.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                prescriptionInfoList.add(detailsBeanX);
            }
        }
        feeDetailResponseBean.setPayAmount(payFee.toString());
        feeDetailResponseBean.setDec(totalFee.toString());
        feeDetailResponseBean.setRecord(prescriptionInfoList);
        return feeDetailResponseBean;
    }

    private List<NewGetFeeDetailResponseBean.DetailsBeanX.DetailsBean> getFeeListBeanList(String feeType, OdsOrderPrescriptionInfo odsPrescriptionInfo, List<OdsOrderPrescriptionDrug> odsPrescriptionDrugList) {
        List<NewGetFeeDetailResponseBean.DetailsBeanX.DetailsBean> medicineListBeans = new ArrayList<>();
        StringBuffer itemName = new StringBuffer();
        BigDecimal totalPrice = new BigDecimal(0);
        BigDecimal totalFee = new BigDecimal(0);
        NewGetFeeDetailResponseBean.DetailsBeanX.DetailsBean detailsBean;
        for (OdsOrderPrescriptionDrug odsPrescriptionDrug : odsPrescriptionDrugList) {
            detailsBean = new NewGetFeeDetailResponseBean.DetailsBeanX.DetailsBean();
            detailsBean.setItemCode(odsPrescriptionDrug.getOrgDrugId());
            detailsBean.setItemName(odsPrescriptionDrug.getDrugName());
            detailsBean.setDosage(odsPrescriptionDrug.getDose() == null ? "0" : odsPrescriptionDrug.getDose() + "");
            detailsBean.setDosageUnit(odsPrescriptionDrug.getDoseUnit());
            detailsBean.setFrequencyCode(odsPrescriptionDrug.getFrequencyCode());
            detailsBean.setDays(odsPrescriptionDrug.getTakeDays() == null ? 0 : odsPrescriptionDrug.getTakeDays());
            detailsBean.setSpecification(odsPrescriptionDrug.getSpecification());
            detailsBean.setUsage(odsPrescriptionDrug.getUsageName());
            detailsBean.setQuantity(odsPrescriptionDrug.getQuantity() == null ? "0" : odsPrescriptionDrug.getQuantity() + "");
            detailsBean.setDecoctionDesc(odsPrescriptionDrug.getDecoctionName());
            detailsBean.setPrice(odsPrescriptionDrug.getPrice() == null ? "0" : odsPrescriptionDrug.getPrice() + "");
            if (FeeTypeEnum.XIYAO.getTitle().equals(feeType) || FeeTypeEnum.CHENGYAO.getTitle().equals(feeType)) {
                detailsBean.setTotalFee(new BigDecimal(detailsBean.getPrice()).multiply(new BigDecimal(detailsBean.getQuantity())).toString());
                medicineListBeans.add(detailsBean);
            } else if (FeeTypeEnum.CAOYAO.getTitle().equals(feeType)) {
                itemName.append(odsPrescriptionDrug.getDrugName()).append(odsPrescriptionDrug.getQuantity()).append(odsPrescriptionDrug.getDoseUnit()).append(" ");
                BigDecimal price = odsPrescriptionDrug.getPrice() == null ? BigDecimal.valueOf(0) : odsPrescriptionDrug.getPrice();
                BigDecimal medicineTotalFee = price.multiply(odsPrescriptionDrug.getQuantity() == null ? BigDecimal.valueOf(0) : odsPrescriptionDrug.getQuantity()).setScale(4, BigDecimal.ROUND_HALF_UP);
                totalFee = totalFee.add(medicineTotalFee.multiply(new BigDecimal(Double.valueOf(String.valueOf(odsPrescriptionInfo.getNumberOfPackets() == null ? 0 : odsPrescriptionInfo.getNumberOfPackets())))));
                totalPrice = totalPrice.add(medicineTotalFee);
            }
        }
        if (FeeTypeEnum.CAOYAO.getTitle().equals(feeType)) {
            detailsBean = new NewGetFeeDetailResponseBean.DetailsBeanX.DetailsBean();
            detailsBean.setItemName(itemName.toString());
            detailsBean.setItemNumber(odsPrescriptionInfo.getNumberOfPackets() == null ? "0" : odsPrescriptionInfo.getNumberOfPackets().toString());
            detailsBean.setQuantity(odsPrescriptionInfo.getNumberOfPackets() == null ? "0" : odsPrescriptionInfo.getNumberOfPackets().toString());
            detailsBean.setPrice(totalPrice.toString());
            detailsBean.setTotalFee(totalPrice.multiply(new BigDecimal(detailsBean.getQuantity())).toString());
            medicineListBeans.add(detailsBean);
        }

        return medicineListBeans;
    }

    /**
     * @description: 获取待支付列表，数据返回和诊间支付的数据返回一致，在hcn-web通过Client.rpcInvoke调用
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/6/18 16:48
     */
    @Override
    @RpcService
    public List<NewQueryUnPayListResponseBean> queryLocalUnPayedRecordList(UnpayedRecordsRequestBean request) throws ControllerException {
        try {
            ValidationUtil.validation(request);//入参格式校验
        } catch (AnnotaionException e) {
            e.printStackTrace();
            throw new ControllerException(e.getMessage());
        }
        try {
            Organization organization = organizationInfoService.getOrgDetailByOrgId(request.getOrgId());

            //返回的待支付列表，每一个对象就是一次问诊的一次处方
            List<NewQueryUnPayListResponseBean> unPayBeanList = new ArrayList<>();
            //费用类型+^+问诊记录标识 为key   费用对象为value
            Map<String, NewQueryUnPayListResponseBean> typeMap = new HashMap<>();

            //诊疗卡号赋值
            Card card = null;
            try {
                card = mpiProvider.getCard(request.getMpiId(), request.getOrgId(), CardTypeEnum.MEDICAL_CARD.getTitle());
            } catch (MPIException e) {
                e.printStackTrace();
            }

            //一个唯一类型+问诊记录的待支付处方或检验、检查 集合
            List<NewQueryUnPayListResponseBean.MergingItemsBean> mergingItems = null;
            //一个唯一类型+问诊记录的待支付处方或检验、检查
            NewQueryUnPayListResponseBean.MergingItemsBean mergingItemsBean;
            //一个唯一类型+问诊记录的待支付处方或检验、检查  的支付明细集合
            List<NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean> detailsItems = null;
            //一个唯一类型+问诊记录的待支付处方或检验、检查  的支付明细
            NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean detailsItemsBean;

            //全部的处方列表
            List<OdsPrescriptionInfo> prescriptionInfoList = prescriptionInfoIntf.findPrescriptionPayList(request.getOrgId(), request.getMpiId());

            QueryDrugOrderListQo qo = new QueryDrugOrderListQo();
            qo.setMpiId(request.getMpiId());
            qo.setUserId(UserRoleToken.getCurrent().getUserId());
            qo.setConsultId("");
            qo.setStatus("1");
            qo.setPageSize(1000);
            qo.setPageNo(1);
            qo.setOutpatientType("2");

            String unPayRecordFlag = "0";
            List<QueryDrugOrderListVo> queryDrugOrderListVos = odsPrescriptionOrderDAO.findOrderList(qo);
            if (CommonUtils.isNotEmpty(queryDrugOrderListVos)) {
                unPayRecordFlag = "1";
            }

            if (CommonUtils.isNotEmpty(prescriptionInfoList)) {
                for (OdsPrescriptionInfo odsPrescriptionInfo : prescriptionInfoList) {
                    ConsultAsk consultAsk = consultAskServiceIntf.getConsultAsksByConsultId(odsPrescriptionInfo.getConsultId());

                    //问诊记录标识为key  的待支付对象
                    NewQueryUnPayListResponseBean unPayBean = typeMap.get(odsPrescriptionInfo.getConsultId());
                    if (null == unPayBean) {
                        unPayBean = new NewQueryUnPayListResponseBean();
                        unPayBean.setDeptName(consultAsk.getDeptName());
                        unPayBean.setConsultId(odsPrescriptionInfo.getConsultId());
                        unPayBean.setTotalFee(0.0D);
                        unPayBean.setConsultTime(consultAsk.getCreateTime());
                        if (card != null) {
                            unPayBean.setPatientMedicalCardNumber(card.getCardNo());
                            unPayBean.setPatientCode(card.getPatientCode());
                        }
                    }
                    //这些处方的总金额
                    BigDecimal totalFee = new BigDecimal(unPayBean.getTotalFee());
                    //获取处方集合
                    mergingItems = unPayBean.getMergingItems();
                    //集合为空，第一次初始化
                    if (null == mergingItems) {
                        mergingItems = new ArrayList<>();
                    }

                    //构建单个处方
                    mergingItemsBean = new NewQueryUnPayListResponseBean.MergingItemsBean();
                    mergingItemsBean.setFeeNo(odsPrescriptionInfo.getPrescriptionInfoId());
                    mergingItemsBean.setConsultId(odsPrescriptionInfo.getConsultId());
                    mergingItemsBean.setDepartmentCode(consultAsk.getLocalDeptId());
                    mergingItemsBean.setDepartmentName(consultAsk.getDeptName());
                    mergingItemsBean.setConsultId(consultAsk.getConsultId());
                    mergingItemsBean.setOrgId(consultAsk.getOrgId());
                    mergingItemsBean.setMedicalDate(DateUtils.toStringForYYYYMMddHHmmss(consultAsk.getCreateTime()));
                    mergingItemsBean.setHospitalName(consultAsk.getOrgName());
                    mergingItemsBean.setHospitalCode(organization.getLocalOrgId());
                    mergingItemsBean.setExpirationDate(CommonUtils.isEmpty(odsPrescriptionInfo.getExpirationDate()) ? "" : DateUtils.toallTime(odsPrescriptionInfo.getExpirationDate()));
                    mergingItemsBean.setWhetherpay(true);
                    mergingItemsBean.setDoctorCode(odsPrescriptionInfo.getLocalDoctorId());
                    mergingItemsBean.setDoctorName(odsPrescriptionInfo.getDoctorName());

                    if (null != mergingItemsBean.getExpirationDate()) {
                        Date expDate = DateUtils.toDateForYYYYMMddHHmmss(mergingItemsBean.getExpirationDate());
                        if (expDate.getTime() > System.currentTimeMillis()) {
                            long time = 0;
                            try {
                                time = DateUtils.getCountTimeMillis(new Date(), expDate);
                                mergingItemsBean.setCountDown(time);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    if ("1".equals(odsPrescriptionInfo.getPrescriptionType())) {
                        mergingItemsBean.setFeeTypeCode(FeeTypeEnum.XIYAO.getTitle());
                        mergingItemsBean.setFeeTypeName(FeeTypeEnum.XIYAO.getContext());
                    } else if ("2".equals(odsPrescriptionInfo.getPrescriptionType())) {
                        mergingItemsBean.setFeeTypeCode(FeeTypeEnum.CHENGYAO.getTitle());
                        mergingItemsBean.setFeeTypeName(FeeTypeEnum.CHENGYAO.getContext());
                    } else if ("3".equals(odsPrescriptionInfo.getPrescriptionType())) {
                        mergingItemsBean.setFeeTypeCode(FeeTypeEnum.CAOYAO.getTitle());
                        mergingItemsBean.setFeeTypeName(FeeTypeEnum.CAOYAO.getContext());
                    }

                    List<NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean> medicineListBeans = new ArrayList<>();
                    List<OdsPrescriptionDrug> odsPrescriptionDrugs = prescriptionInfoIntf.findByPrescriptionInfoId(odsPrescriptionInfo.getPrescriptionInfoId());

                    medicineListBeans = getDetailsItemsBeanList(odsPrescriptionInfo, odsPrescriptionDrugs, mergingItemsBean);

                    mergingItemsBean.setDetailsItems(medicineListBeans);

                    mergingItems.add(mergingItemsBean);
                    //算总金额
                    totalFee = totalFee.add(new BigDecimal(mergingItemsBean.getMergingSubtotal())).setScale(2, BigDecimal.ROUND_HALF_UP);
                    unPayBean.setMergingItems(mergingItems);
                    unPayBean.setTotalFee(totalFee.doubleValue());
                    unPayBean.setUnPayRecordFlag(unPayRecordFlag);

                    typeMap.put(odsPrescriptionInfo.getConsultId(), unPayBean);
                }
            }

            Person person = mpiProvider.getPerson(request.getMpiId());
            Certificate certificate = person.getCertificate();
            // TODO: 2020/6/18  查询费用表，要添加支付状态，目前还未定支付状态字典
            LOGGER.info(" 待支付列表 queryLocalUnPayedRecordList 查询开始 ： orgId:" + organization.getOrgId() + " cardNumber: " + SM4Utils.decryptData_ECB(certificate.getCertificateNo()));
            List<DisposalExpenseRecord> disposalExpenseRecords = disposalExpenseRecordServiceIntf.queryByHospitalCode(organization.getLocalOrgId(), SM4Utils.decryptData_ECB(certificate.getCertificateNo()), "0");
            LOGGER.info(" 待支付列表 queryLocalUnPayedRecordList 结果 ： " + JSONUtils.writeValueAsString(disposalExpenseRecords));
            if (CommonUtils.isNotEmpty(disposalExpenseRecords)) {
                if (CommonUtils.isEmpty(mergingItems)) {
                    mergingItems = new ArrayList<>();
                }
                for (DisposalExpenseRecord disposalExpenseRecord : disposalExpenseRecords) {
                    ConsultAsk consultAsk = consultAskServiceIntf.getConsultAsksByConsultId(disposalExpenseRecord.getConsultId());
                    //问诊记录标识为key  的待支付对象
                    NewQueryUnPayListResponseBean unPayBean = typeMap.get(disposalExpenseRecord.getConsultId());
                    if (null == unPayBean) {
                        unPayBean = new NewQueryUnPayListResponseBean();
                        unPayBean.setDeptName(consultAsk.getDeptName());
                        unPayBean.setConsultId(disposalExpenseRecord.getConsultId());
                        unPayBean.setTotalFee(0.0D);
                        unPayBean.setConsultTime(consultAsk.getCreateTime());
                        if (card != null) {
                            unPayBean.setPatientMedicalCardNumber(card.getCardNo());
                            unPayBean.setPatientCode(card.getPatientCode());
                        }
                    }
                    BigDecimal beanTotalFee = new BigDecimal(unPayBean.getTotalFee());
                    mergingItems = unPayBean.getMergingItems();
                    if (null == mergingItems) {
                        mergingItems = new ArrayList<>();
                    }
                    //组装检验、检查对象
                    mergingItemsBean = new NewQueryUnPayListResponseBean.MergingItemsBean();
                    mergingItemsBean.setFeeNo(disposalExpenseRecord.getExpenseId());
                    mergingItemsBean.setDepartmentCode(disposalExpenseRecord.getApplyDepartmentId());
                    mergingItemsBean.setDepartmentName(disposalExpenseRecord.getApplyDepartmentName());
                    mergingItemsBean.setConsultId(consultAsk.getConsultId());
                    mergingItemsBean.setOrgId(consultAsk.getOrgId());
                    mergingItemsBean.setMedicalDate(DateUtils.toStringForYYYYMMddHHmmss(consultAsk.getCreateTime()));
                    mergingItemsBean.setHospitalName(consultAsk.getOrgName());
                    mergingItemsBean.setDoctorCode(disposalExpenseRecord.getApplyDoctorId());
                    mergingItemsBean.setDoctorName(disposalExpenseRecord.getApplyDoctorName());
                    mergingItemsBean.setWhetherpay(true);
                    mergingItemsBean.setExpirationDate(CommonUtils.isEmpty(disposalExpenseRecord.getExpirationDate()) ? "" : DateUtils.toallTime(disposalExpenseRecord.getExpirationDate()));
                    mergingItemsBean.setItemName(disposalExpenseRecord.getItemName());
                    mergingItemsBean.setMergingName(disposalExpenseRecord.getItemName());
                    if (null != disposalExpenseRecord.getExpirationDate()) {
                        if (disposalExpenseRecord.getExpirationDate().getTime() > System.currentTimeMillis()) {
                            long time = 0;
                            try {
                                time = DateUtils.getCountTimeMillis(new Date(), disposalExpenseRecord.getExpirationDate());
                                mergingItemsBean.setCountDown(time);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    //支付有效期(分钟)
                    BasePropertyConfig basePropertyConfig = null;
                    //默认添加
                    boolean addFlag = true;
                    //检验
                    if (FeeTypeEnum.JIANYAN.getTitle().equals(disposalExpenseRecord.getBillCategoryCode())) {
                        mergingItemsBean.setFeeTypeCode(FeeTypeEnum.JIANYAN.getTitle());
                        mergingItemsBean.setFeeTypeName(FeeTypeEnum.JIANYAN.getContext());
                        mergingItemsBean.setExamineRequisitionRecordId(prescriptionInfoIntf.getExamineIdByApplicationNo(disposalExpenseRecord.getApplicationNo(), organization.getLocalOrgId()));
                        //<item key="013803" text="检验预约支付倒计时间(单位:分钟)，默认:30"/>
                        basePropertyConfig = serviceOpenService.getBasePropertyConfig("013803", request.getOrgId());
                    } else if (FeeTypeEnum.JIANCHA.getTitle().equals(disposalExpenseRecord.getBillCategoryCode())) {
                        //检查
                        mergingItemsBean.setFeeTypeCode(FeeTypeEnum.JIANCHA.getTitle());
                        mergingItemsBean.setFeeTypeName(FeeTypeEnum.JIANCHA.getContext());
                        mergingItemsBean.setCheckRequisitionRecordId(prescriptionInfoIntf.getCheckIdByApplicationNo(disposalExpenseRecord.getApplicationNo(), organization.getLocalOrgId()));
                        //<item key="011216" text="检查预约支付倒计时间(单位:分钟)，默认:30"/>
                        basePropertyConfig = serviceOpenService.getBasePropertyConfig("011216", request.getOrgId());
                    } else if (FeeTypeEnum.ZHILIAO.getTitle().equals(disposalExpenseRecord.getBillCategoryCode())) {
                        //治疗
                        mergingItemsBean.setFeeTypeCode(FeeTypeEnum.ZHILIAO.getTitle());
                        mergingItemsBean.setFeeTypeName(FeeTypeEnum.ZHILIAO.getContext());
                        mergingItemsBean.setCheckRequisitionRecordId(disposalExpenseRecord.getItemId());
                        //<item key="011216" text="检查预约支付倒计时间(单位:分钟)，默认:30"/>
                        basePropertyConfig = serviceOpenService.getBasePropertyConfig("011216", request.getOrgId());

                    }

                    //查询申请单预约记录
                    List<CheckAppointmentRecord> checkAppointmentRecords = disposalExpenseRecordServiceIntf.queryCheckRequestNumberAndAppointmentHospitalCode(disposalExpenseRecord.getApplicationNo(), disposalExpenseRecord.getOrganizationId());
                    //未预约随时可以支付
                    if (CommonUtils.isEmpty(checkAppointmentRecords)) {
                        addFlag = true;
                        //已预约要根据时间判断过期
                    } else {
                        if (null != basePropertyConfig) {
                            Long current = System.currentTimeMillis();
                            //检查预约操作时间
                            Date applyTime = checkAppointmentRecords.get(0).getCreateTime();
                            if (null != applyTime) {
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTime(applyTime);
                                calendar.add(Calendar.MINUTE, Integer.valueOf(basePropertyConfig.getPropertyData()));
                                //若是申请时间加上支付过期时间 小于 当前时间 ，不返回
                                if (current > calendar.getTimeInMillis()) {
                                    addFlag = false;
                                }
                                mergingItemsBean.setCountDown(calendar.getTimeInMillis() - current);
                            }
                        }
                    }

                    //若是未超时
                    if (addFlag) {
                        List<DisposalExpenseDetail> disposalExpenseDetails = disposalExpenseRecordServiceIntf.queryDisposalExpenseDetail(disposalExpenseRecord.getExpenseId());
                        if (CommonUtils.isNotEmpty(disposalExpenseDetails)) {
                            detailsItems = new ArrayList<>();
                            BigDecimal totalFee = new BigDecimal(0);
                            for (DisposalExpenseDetail disposalExpenseDetail : disposalExpenseDetails) {
                                detailsItemsBean = new NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean();
                                detailsItemsBean.setItemName(disposalExpenseDetail.getItemName());
                                Double quantity = disposalExpenseDetail.getNumber() == null ? 0 : disposalExpenseDetail.getNumber().doubleValue();
                                detailsItemsBean.setItemNumber(quantity.toString());
                                Double price = disposalExpenseDetail.getPrice() == null ? 0 : disposalExpenseDetail.getPrice().doubleValue();
                                detailsItemsBean.setPrice(price);
                                detailsItemsBean.setUnit(disposalExpenseDetail.getUnit());
                                double amount = disposalExpenseDetail.getAmount() == null ? 0 : disposalExpenseDetail.getAmount().doubleValue();
                                totalFee = totalFee.add(new BigDecimal(amount));
                                detailsItemsBean.setAmount(amount);
                                detailsItems.add(detailsItemsBean);
                            }
                            mergingItemsBean.setMergingSubtotal(totalFee.doubleValue());
                            mergingItemsBean.setDetailsItems(detailsItems);
                        }
                        mergingItems.add(mergingItemsBean);
                        beanTotalFee = beanTotalFee.add(new BigDecimal(mergingItemsBean.getMergingSubtotal())).setScale(2, BigDecimal.ROUND_HALF_UP);
                        unPayBean.setMergingItems(mergingItems);
                        unPayBean.setTotalFee(beanTotalFee.doubleValue());

                        unPayBean.setUnPayRecordFlag(unPayRecordFlag);
                        typeMap.put(disposalExpenseRecord.getConsultId(), unPayBean);
                    }
                }
            }

            if (CommonUtils.isNotEmpty(typeMap.keySet())) {
                unPayBeanList.addAll(typeMap.values());
                Collections.sort(unPayBeanList, new Comparator<NewQueryUnPayListResponseBean>() {
                    @Override
                    public int compare(NewQueryUnPayListResponseBean o1, NewQueryUnPayListResponseBean o2) {
                        Long date1 = o1.getConsultTime().getTime();
                        Long date2 = o2.getConsultTime().getTime();
                        return date2.compareTo(date1);
                    }
                });
            }

            if (CommonUtils.isEmpty(unPayBeanList)) {
                NewQueryUnPayListResponseBean newQueryUnPayListResponseBean = new NewQueryUnPayListResponseBean();
                newQueryUnPayListResponseBean.setUnPayRecordFlag(unPayRecordFlag);
                unPayBeanList.add(newQueryUnPayListResponseBean);
            }
            return unPayBeanList;

        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("获取待支付列表失败");
        }
    }


    /**
     * @description: 自主开单待支付列表
     */
    @Override
    @RpcService
    public List<NewQueryUnPayListResponseBean> queryNatUnPayedRecordList(UnpayedRecordsRequestBean request) throws ControllerException {
        try {
            ValidationUtil.validation(request);//入参格式校验
        } catch (AnnotaionException e) {
            e.printStackTrace();
            throw new ControllerException(e.getMessage());
        }
        try {
            Organization organization = organizationInfoService.getOrgDetailByOrgId(request.getOrgId());

            //返回的待支付列表，每一个对象就是一次问诊的一次处方
            List<NewQueryUnPayListResponseBean> unPayBeanList = new ArrayList<>();
            //费用类型+^+问诊记录标识 为key   费用对象为value
            Map<String, NewQueryUnPayListResponseBean> typeMap = new HashMap<>();

            //诊疗卡号赋值
            Card card = null;
            try {
                card = mpiProvider.getCard(request.getMpiId(), request.getOrgId(), CardTypeEnum.MEDICAL_CARD.getTitle());
            } catch (MPIException e) {
                e.printStackTrace();
            }
            String unPayRecordFlag = "0";

            //一个唯一类型+问诊记录的待支付处方或检验、检查 集合
            List<NewQueryUnPayListResponseBean.MergingItemsBean> mergingItems = null;
            //一个唯一类型+问诊记录的待支付处方或检验、检查
            NewQueryUnPayListResponseBean.MergingItemsBean mergingItemsBean;
            //一个唯一类型+问诊记录的待支付处方或检验、检查  的支付明细集合
            List<NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean> detailsItems = null;
            //一个唯一类型+问诊记录的待支付处方或检验、检查  的支付明细
            NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean detailsItemsBean;

            
            Person person = mpiProvider.getPerson(request.getMpiId());
            Certificate certificate = person.getCertificate();
            LOGGER.info(" 待支付列表 queryLocalUnPayedRecordList 查询开始 ： orgId:" + organization.getOrgId() + " cardNumber: " + SM4Utils.decryptData_ECB(certificate.getCertificateNo()));
            List<DisposalExpenseRecord> disposalExpenseRecords = disposalExpenseRecordServiceIntf.queryByHospitalCodeAndBusinessType(organization.getLocalOrgId(), SM4Utils.decryptData_ECB(certificate.getCertificateNo()), "0", "2");
            LOGGER.info(" 待支付列表 queryLocalUnPayedRecordList 结果 ： " + JSONUtils.writeValueAsString(disposalExpenseRecords));
            if (CommonUtils.isNotEmpty(disposalExpenseRecords)) {
                if (CommonUtils.isEmpty(mergingItems)) {
                    mergingItems = new ArrayList<>();
                }
                for (DisposalExpenseRecord disposalExpenseRecord : disposalExpenseRecords) {
                    NatSubmitRecordVo natVo = consultAskServiceIntf.getNatRecordById(disposalExpenseRecord.getConsultId());
                    //问诊记录标识为key  的待支付对象
                    NewQueryUnPayListResponseBean unPayBean = typeMap.get(disposalExpenseRecord.getConsultId());
                    if (null == unPayBean) {
                        unPayBean = new NewQueryUnPayListResponseBean();
                        unPayBean.setDeptName(natVo.getDepartmentName());
                        unPayBean.setConsultId(disposalExpenseRecord.getConsultId());
                        unPayBean.setTotalFee(0.0D);
                        unPayBean.setConsultTime(natVo.getCreateTime());
                        if (card != null) {
                            unPayBean.setPatientMedicalCardNumber(card.getCardNo());
                            unPayBean.setPatientCode(card.getPatientCode());
                        }
                    }
                    BigDecimal beanTotalFee = new BigDecimal(unPayBean.getTotalFee());
                    mergingItems = unPayBean.getMergingItems();
                    if (null == mergingItems) {
                        mergingItems = new ArrayList<>();
                    }
                    //组装检验、检查对象
                    mergingItemsBean = new NewQueryUnPayListResponseBean.MergingItemsBean();
                    mergingItemsBean.setFeeNo(disposalExpenseRecord.getExpenseIdSource());
                    mergingItemsBean.setDepartmentCode(disposalExpenseRecord.getApplyDepartmentId());
                    mergingItemsBean.setDepartmentName(disposalExpenseRecord.getApplyDepartmentName());
                    mergingItemsBean.setConsultId(natVo.getNatSubmitRecordId());
                    mergingItemsBean.setOrgId(request.getOrgId());
                    mergingItemsBean.setMedicalDate(DateUtils.toStringForYYYYMMddHHmmss(natVo.getCreateTime()));
                    mergingItemsBean.setHospitalName(natVo.getOrganizationName());
                    mergingItemsBean.setDoctorCode(disposalExpenseRecord.getApplyDoctorId());
                    mergingItemsBean.setDoctorName(disposalExpenseRecord.getApplyDoctorName());
                    mergingItemsBean.setWhetherpay(true);
                    mergingItemsBean.setExpirationDate(CommonUtils.isEmpty(disposalExpenseRecord.getExpirationDate()) ? "" : DateUtils.toallTime(disposalExpenseRecord.getExpirationDate()));
                    mergingItemsBean.setItemName(disposalExpenseRecord.getItemName());
                    mergingItemsBean.setMergingName(disposalExpenseRecord.getItemName());
                    if (null != disposalExpenseRecord.getExpirationDate()) {
                        if (disposalExpenseRecord.getExpirationDate().getTime() > System.currentTimeMillis()) {
                            long time = 0;
                            try {
                                time = DateUtils.getCountTimeMillis(new Date(), disposalExpenseRecord.getExpirationDate());
                                mergingItemsBean.setCountDown(time);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    //支付有效期(分钟)
                    BasePropertyConfig basePropertyConfig = null;
                    //默认添加
                    boolean addFlag = true;
                    //检验
                    if (FeeTypeEnum.JIANYAN.getTitle().equals(disposalExpenseRecord.getBillCategoryCode())) {
                        mergingItemsBean.setFeeTypeCode(FeeTypeEnum.JIANYAN.getTitle());
                        mergingItemsBean.setFeeTypeName(FeeTypeEnum.JIANYAN.getContext());
                        mergingItemsBean.setExamineRequisitionRecordId(prescriptionInfoIntf.getExamineIdByApplicationNo(disposalExpenseRecord.getApplicationNo(), organization.getLocalOrgId()));
                        //<item key="013803" text="检验预约支付倒计时间(单位:分钟)，默认:30"/>
                        basePropertyConfig = serviceOpenService.getBasePropertyConfig("013803", request.getOrgId());
                    } else if (FeeTypeEnum.JIANCHA.getTitle().equals(disposalExpenseRecord.getBillCategoryCode())) {
                        //检查
                        mergingItemsBean.setFeeTypeCode(FeeTypeEnum.JIANCHA.getTitle());
                        mergingItemsBean.setFeeTypeName(FeeTypeEnum.JIANCHA.getContext());
                        mergingItemsBean.setCheckRequisitionRecordId(prescriptionInfoIntf.getCheckIdByApplicationNo(disposalExpenseRecord.getApplicationNo(), organization.getLocalOrgId()));
                        //<item key="011216" text="检查预约支付倒计时间(单位:分钟)，默认:30"/>
                        basePropertyConfig = serviceOpenService.getBasePropertyConfig("011216", request.getOrgId());
                    }

                    //查询申请单预约记录
                    List<CheckAppointmentRecord> checkAppointmentRecords = disposalExpenseRecordServiceIntf.queryCheckRequestNumberAndAppointmentHospitalCode(disposalExpenseRecord.getApplicationNo(), disposalExpenseRecord.getOrganizationId());
                    //未预约随时可以支付
                    if (CommonUtils.isEmpty(checkAppointmentRecords)) {
                        addFlag = true;
                        //已预约要根据时间判断过期
                    } else {
                        if (null != basePropertyConfig) {
                            Long current = System.currentTimeMillis();
                            //检查预约操作时间
                            Date applyTime = checkAppointmentRecords.get(0).getCreateTime();
                            if (null != applyTime) {
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTime(applyTime);
                                calendar.add(Calendar.MINUTE, Integer.valueOf(basePropertyConfig.getPropertyData()));
                                //若是申请时间加上支付过期时间 小于 当前时间 ，不返回
                                if (current > calendar.getTimeInMillis()) {
                                    addFlag = false;
                                }
                                mergingItemsBean.setCountDown(calendar.getTimeInMillis() - current);
                            }
                        }
                    }

                    //若是未超时
                    if (addFlag) {
                        List<DisposalExpenseDetail> disposalExpenseDetails = disposalExpenseRecordServiceIntf.queryDisposalExpenseDetail(disposalExpenseRecord.getExpenseId());
                        if (CommonUtils.isNotEmpty(disposalExpenseDetails)) {
                            detailsItems = new ArrayList<>();
                            BigDecimal totalFee = new BigDecimal(0);
                            for (DisposalExpenseDetail disposalExpenseDetail : disposalExpenseDetails) {
                                detailsItemsBean = new NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean();
                                detailsItemsBean.setItemName(disposalExpenseDetail.getItemName());
                                Double quantity = disposalExpenseDetail.getNumber() == null ? 0 : disposalExpenseDetail.getNumber().doubleValue();
                                detailsItemsBean.setItemNumber(quantity.toString());
                                Double price = disposalExpenseDetail.getPrice() == null ? 0 : disposalExpenseDetail.getPrice().doubleValue();
                                detailsItemsBean.setPrice(price);
                                detailsItemsBean.setUnit(disposalExpenseDetail.getUnit());
                                double amount = disposalExpenseDetail.getAmount() == null ? 0 : disposalExpenseDetail.getAmount().doubleValue();
                                totalFee = totalFee.add(new BigDecimal(amount));
                                detailsItemsBean.setAmount(amount);
                                detailsItems.add(detailsItemsBean);
                            }
                            mergingItemsBean.setMergingSubtotal(totalFee.doubleValue());
                            mergingItemsBean.setDetailsItems(detailsItems);
                        }
                        mergingItems.add(mergingItemsBean);
                        beanTotalFee = beanTotalFee.add(new BigDecimal(mergingItemsBean.getMergingSubtotal())).setScale(2, BigDecimal.ROUND_HALF_UP);
                        unPayBean.setMergingItems(mergingItems);
                        unPayBean.setTotalFee(beanTotalFee.doubleValue());

                        unPayBean.setUnPayRecordFlag(unPayRecordFlag);
                        typeMap.put(disposalExpenseRecord.getConsultId(), unPayBean);
                    }
                }
            }

            if (CommonUtils.isNotEmpty(typeMap.keySet())) {
                unPayBeanList.addAll(typeMap.values());
                Collections.sort(unPayBeanList, new Comparator<NewQueryUnPayListResponseBean>() {
                    @Override
                    public int compare(NewQueryUnPayListResponseBean o1, NewQueryUnPayListResponseBean o2) {
                        Long date1 = o1.getConsultTime().getTime();
                        Long date2 = o2.getConsultTime().getTime();
                        return date2.compareTo(date1);
                    }
                });
            }

            if (CommonUtils.isEmpty(unPayBeanList)) {
                NewQueryUnPayListResponseBean newQueryUnPayListResponseBean = new NewQueryUnPayListResponseBean();
                newQueryUnPayListResponseBean.setUnPayRecordFlag(unPayRecordFlag);
                unPayBeanList.add(newQueryUnPayListResponseBean);
            }
            return unPayBeanList;

        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("获取待支付列表失败");
        }
    }


}
